package com.lubase.export.controller;

import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.lubase.core.config.PassToken;
import com.lubase.core.entity.SsPageEntity;
import com.lubase.core.response.ResponseData;
import com.lubase.core.service.AppFuncDataService;
import com.lubase.core.service.MethodAdapterService;
import com.lubase.core.service.RenderTableService;
import com.lubase.core.util.ClientMacro;
import com.lubase.export.service.ExportsExtendService;
import com.lubase.orm.QueryOption;
import com.lubase.orm.TableFilter;
import com.lubase.orm.exception.InvokeCommonException;
import com.lubase.orm.exception.WarnCommonException;
import com.lubase.orm.model.DbCollection;
import com.lubase.orm.util.ServerMacroService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/Export")
public class ExportController {
    @Autowired
    ExportsExtendService exportService;

    @Autowired
    RenderTableService pageDataService;

    @Autowired
    ServerMacroService serverMacroService;

    @Autowired
    MethodAdapterService methodAdapterService;

    @Autowired
    AppFuncDataService appFuncDataService;

    @Autowired
    RenderTableService renderTableService;

    /**
     * 当前页面下载
     *
     * @param map pageId,queryParam,clientMacro,name
     * @param response 返回流
     */
    @RequestMapping(value = "/download", method = RequestMethod.POST)
    public void fileDownload(@RequestBody Map<String, String> map, HttpServletResponse response) throws InvokeCommonException, IOException {
        String pageId = "", queryParam = "",name = "",suffixes="",searchParam="",fullTextSearch="";
        Map<String, String> maps = MapUtils.newHashMap();
        maps.put("status", "failure");

        ClientMacro clientMacro = null;
        if (map.containsKey("pageId")) {
            pageId = map.get("pageId");
        }
        if (StringUtils.isEmpty(pageId)) {

            throw new InvokeCommonException("pageId不存在");
        }
        if (map.containsKey("queryParam")) {
            queryParam = map.get("queryParam");
        }
        if (map.containsKey("name")) {
            name = map.get("name");
        }
        if (map.containsKey("suffixes")) {
            suffixes = map.get("suffixes");
        }
        if (map.containsKey("searchParam")) {
            searchParam =map.get("searchParam");
        }
        if (map.containsKey("fullTextSearch")) {
            fullTextSearch =map.get("fullTextSearch");
        }
        if (map.containsKey("clientMacro")) {
            clientMacro = ClientMacro.init(map.get("clientMacro"));
        } else {
            response.getWriter().println(JSON.toJSONString(map));
        }
        DbCollection collection =  pageDataService.getGridDataByPageId(pageId, clientMacro,searchParam, queryParam, fullTextSearch);
        exportService.ExportByQuery(collection,response,name,suffixes);
    }

    @SneakyThrows
    @RequestMapping(value = "/exportStatisticInfoData", method = RequestMethod.POST)
    public void exportStatisticInfoData(@RequestBody Map<String, String> map, HttpServletResponse response) {
        String pageId = "", queryParam = "", rowValue = "", colValue = "",suffixes="";;
        ClientMacro clientMacro = null;
        if (map.containsKey("pageId")) {
            pageId = map.get("pageId");
        }
        if (StringUtils.isEmpty(pageId)) {
            throw new InvokeCommonException("pageId  not found");
        }
        if (map.containsKey("queryParam")) {
            queryParam = map.get("queryParam");
        }
        if (map.containsKey("clientMacro")) {
            clientMacro = ClientMacro.init(map.get("clientMacro"));
        } else {
            throw new InvokeCommonException("clientMacro  not found");
        }
        if (map.containsKey("rowValue")) {
            rowValue = map.get("rowValue");
        }
        if (map.containsKey("colValue")) {
            colValue = map.get("colValue");
        }
        if (map.containsKey("suffixes")) {
            suffixes = map.get("suffixes");
        }
        DbCollection collection = renderTableService.getStatisticsInfoNoPaging(pageId, queryParam, clientMacro, rowValue, colValue);
        String name = collection.getTableInfo().getName();
        exportService.ExportByQuery(collection, response, name,suffixes);
    }

    /**
     * 全量下载
     * @param map pageId,queryParam,clientMacro,name
     * @param response 返回流
     */
    @RequestMapping(value = "/downloadAll", method = RequestMethod.POST)
    public void fileDownloadAll(@RequestBody Map<String, String> map, HttpServletResponse response) throws InvokeCommonException, IOException {
        String pageId = "", queryParam = "",name = "",suffixes="";
        Map<String, String> maps = MapUtils.newHashMap();
        maps.put("status", "failure");

        ClientMacro clientMacro = null;
        if (map.containsKey("pageId")) {
            pageId = map.get("pageId");
        }
        if (StringUtils.isEmpty(pageId)) {
            throw new  InvokeCommonException("pageId不存在");
        }
        if (map.containsKey("queryParam")) {
            queryParam = map.get("queryParam");
        }
        if (map.containsKey("name")) {
            name = map.get("name");
        }
        if (map.containsKey("suffixes")) {
            suffixes = map.get("suffixes");
        }
        if (map.containsKey("clientMacro")) {
            clientMacro = ClientMacro.init(map.get("clientMacro"));
        } else {
            response.getWriter().println(JSON.toJSONString(map));
        }
        SsPageEntity pageEntity = appFuncDataService.getPageById(pageId);
        if (pageEntity != null && !StringUtils.isEmpty(pageEntity.getGrid_query())) {
            QueryOption serverQuery = JSON.parseObject(pageEntity.getGrid_query(), QueryOption.class);
            QueryOption clientQuery = JSON.parseObject(queryParam, QueryOption.class);

            if (clientQuery != null) {
                if (!StringUtils.isEmpty(clientQuery.getSortField())) {
                    serverQuery.setSortField(clientQuery.getSortField());
                }

                if (clientQuery.getTableFilter() != null) {
                    serverQuery.getTableFilter().getChildFilters().add(clientQuery.getTableFilter());
                }
            }
            //替换宏变量
            replaceClientMacro(serverQuery.getTableFilter(), clientMacro);
            if (StringUtils.isEmpty(serverQuery.getFixField())) {
                serverQuery.setFixField("*");
            }
            exportService.ExportByQueryAll(serverQuery,response,name, suffixes);

        }
    }
    /**
     * 选择行批量下载
     * @param listMapParam id,TableId
     * @param response 返回流
     */
    @RequestMapping(value = "/download2", method = RequestMethod.POST)
    public void fileDownload(@RequestBody List<HashMap<String, String>> listMapParam, HttpServletResponse response) throws InvokeCommonException, IOException {
        List<String> IDList = new ArrayList<>();
        String TableId ="";
        for (Map<String, String> MapParam:listMapParam) {
            IDList.add(MapParam.get("Id"));
            TableId = MapParam.get("TableId");
        }
        String Ids = org.apache.commons.lang3.StringUtils.join(IDList,',');
        if(org.apache.commons.lang3.StringUtils.isBlank(Ids)){
            throw new InvokeCommonException("无选中项");
        }
        exportService.ExportByIds(TableId,Ids,response);
    }

    /**
     * 下载模板
     * @param map tableName
     * @param response 返回流
     */
    @SneakyThrows
    @RequestMapping(value = "/downloadModel", method = RequestMethod.POST)
    public void downloadModel(@RequestBody Map<String, String> map, HttpServletResponse response)  {
        String tableName = "",tableId="";
        if (map.containsKey("tableName")) {
            tableName = map.get("tableName");
        }
        if (map.containsKey("tableId")) {
            tableId = map.get("tableId");
        }
        if(StringUtils.isEmpty(tableName)&&StringUtils.isEmpty(tableId))
        {
            throw new WarnCommonException("参数不能为空");
        }
        exportService.ExportModel(tableName,tableId,response);
    }
    /**
     * 导入模板
     * @param tableName，file
     */
    @SneakyThrows
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public ResponseData<String> importExcel (@RequestParam  String tableName, @RequestParam  String tableId, @RequestParam MultipartFile file){
        if (file.getBytes().length == 0) {
            throw new WarnCommonException("不能上传空文件");
        }
        if(StringUtils.isEmpty(tableName)&&StringUtils.isEmpty(tableId))
        {
            throw new WarnCommonException("参数不能为空");
        }
        exportService.Import(tableName,tableId,file);
        return  ResponseData.success("导入成功!");

    }

    /**
     * 宏变量替换
     * @param tableFilter 标准的TableFilter
     * @param clientMacro 客户端宏变量
     */
    void replaceClientMacro(TableFilter tableFilter, ClientMacro clientMacro) {
        if (tableFilter.getChildFilters() != null) {
            for (TableFilter filter : tableFilter.getChildFilters()) {
                replaceClientMacro(filter, clientMacro);
            }
        } else {
            Object objectVal = tableFilter.getFilterValue();
            if (objectVal == null || StringUtils.isEmpty(objectVal)) {
                return;
            }
            String strVal = objectVal.toString();
            // 必须客户端宏变量不为空才可以替换，否则无值此条件会作废
            if (strVal.startsWith(ClientMacro.clientMacroPre)) {
                //替换宏变量
                if (clientMacro.containsKey(strVal)
                        && !StringUtils.isEmpty(clientMacro.get(strVal))) {
                    tableFilter.setFilterValue(clientMacro.get(strVal));
                } else {
                    //设置一个不存在的条件
                    tableFilter.setFilterName("id");
                    tableFilter.setFilterValue(0);
                }
            } else if (strVal.startsWith(ClientMacro.serverMacroPre)) {
                tableFilter.setFilterValue(serverMacroService.getServerMacroByKey(strVal));
            }
        }
    }

}
